package com.group15.phms;


import java.util.ArrayList;
import java.util.Date;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;
import android.view.MenuItem;


/** Activity which displays a login screen to the user, offering registration as well.*/
public class Login extends Activity {
	/**Authentication store containing known user names and passwords.*/
	SharedPreferences logins;
	DatabaseHelper db;
	

	/**The default user name to populate the user name field with.*/
	public static final String EXTRA_EMAIL = "defaultName";

	/**Keep track of the login task to ensure we can cancel it if requested.*/
	private UserLoginTask mAuthTask = null;

	// Values for user name and password at the time of the login attempt.
	private String mUserName;
	private String mPassword;

	// UI references.
	private EditText mUserNameView;
	private EditText mPasswordView;
	private View mLoginFormView;
	private View mLoginStatusView;
	private TextView mLoginStatusMessageView;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_login);

		logins = getSharedPreferences("logins",MODE_PRIVATE);
		db= new DatabaseHelper(getApplicationContext());
		
		// Set up the login form.
		mUserName = getIntent().getStringExtra(EXTRA_EMAIL);
		mUserNameView = (EditText) findViewById(R.id.username);
		mUserNameView.setText(mUserName);

		mPasswordView = (EditText) findViewById(R.id.password);
		mPasswordView
				.setOnEditorActionListener(new TextView.OnEditorActionListener() {
					@Override
					public boolean onEditorAction(TextView textView, int id,
							KeyEvent keyEvent) {
						if (id == R.id.login || id == EditorInfo.IME_NULL) {
							attemptLogin();
							return true;
						}
						return false;
					}
				});

		mLoginFormView = findViewById(R.id.login_form);
		mLoginStatusView = findViewById(R.id.login_status);
		mLoginStatusMessageView = (TextView) findViewById(R.id.login_status_message);
		
		//#################### Test Data Remove Before Production ####################
		SharedPreferences.Editor editor = logins.edit();
		editor.putString("admin","password");
		editor.commit();
		db.addUser(new User("Sam Smith", "admin", "password", "name@domain.com", "1-1-1993"));
		
		db.addMedication(new Medication("Afrin","Oxymetazoline"),"admin");
		db.addMedication(new Medication("Tylenol","Acetaminophen"),"admin");
		db.addMedication(new Medication("Zyrtec","Cetirizine"),"admin");
		db.addMedication(new Medication("Blood Pressure","lisinopril"),"admin");
		
		db.addDose(new Dose("2","Sprays",9,00), "admin", "Oxymetazoline");
		db.addDose(new Dose("2","Caplets",11,00), "admin", "Acetaminophen");
		db.addDose(new Dose("1","Pill",20,00), "admin", "Cetirizine");
		db.addDose(new Dose("2","Caplets",9,00), "admin", "lisinopril");
		
		db.addVitals(new VitalSigns(100, 100, 120, 80, new Date(System.currentTimeMillis())), "admin");
		
		db.addDoctor((new Doctor("Dr. Watson","watson@hotmail.com")), "admin");
		db.addDoctor((new Doctor("Dr. Collins","scollins@collinsfamilycare.com")), "admin");
   		
		db.addContact((new Contact("John Smith","jsmith@gmail.com","8172728888")), "admin");
		db.addContact((new Contact("Jane Doe","jdoe@hotmail.com","7132225555")), "admin");
		
		db.addNote("admin", new Note("Interesting Link", "I found a great website which helps me find things: www.google.com"));
		db.addNote("admin", new Note("Things to remember", "Dont forget to take blood pressure."));
		
		db.closeDB();
		
		//#################### End Test Data ####################
		

		findViewById(R.id.sign_in_button).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View view) {
						attemptLogin();
					}
				});
		findViewById(R.id.register_button).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View view) {
						attemptRegistration();
					}
				});
	}//END onCreate

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		int id = item.getItemId();
		if (id == R.id.action_forgot_password) {
			// This ID represents the Home or Up button. In the case of this activity, the Up button is shown.
			recoverPassword();
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		getMenuInflater().inflate(R.menu.login, menu);
		return true;
	}

	/**
	 * Attempts to sign in.
	 * If there are form errors (invalid fields, missing fields, etc.), the
	 * errors are presented and no actual login attempt is made.
	 */
	public void attemptLogin() {
		if (mAuthTask != null) {
			return;
		}

		// Reset errors.
		mUserNameView.setError(null);
		mPasswordView.setError(null);

		// Store values at the time of the login attempt.
		mUserName = mUserNameView.getText().toString();
		mPassword = mPasswordView.getText().toString();

		boolean cancel = false;
		View focusView = null;

		// Check for a valid password.
		if (TextUtils.isEmpty(mPassword)) {
			mPasswordView.setError(getString(R.string.error_field_required));
			focusView = mPasswordView;
			cancel = true;
		} else if (mPassword.length() < 4) {
			mPasswordView.setError(getString(R.string.error_invalid_password));
			focusView = mPasswordView;
			cancel = true;
		}

		// Check for a valid user name.
		if (TextUtils.isEmpty(mUserName)) {
			mUserNameView.setError(getString(R.string.error_field_required));
			focusView = mUserNameView;
			cancel = true;
		}

		if (cancel) {
			// There was an error; don't attempt login and focus the first form field with an error.
			focusView.requestFocus();
		} else {
			// Show a progress spinner, and kick off a background task to perform the user login attempt.
			mLoginStatusMessageView.setText(R.string.login_progress_signing_in);
			showProgress(true);
			mAuthTask = new UserLoginTask();
			mAuthTask.execute((Void) null);
		}
	}
	
	void recoverPassword()
	{
		
		
				
		/*
		Intent i = new Intent(Intent.ACTION_SEND);
		i.setType("message/rfc822");
		i.putExtra(Intent.EXTRA_EMAIL  , new String[]{"generalbraden@live.com"});
		i.putExtra(Intent.EXTRA_SUBJECT, "subject of email");
		i.putExtra(Intent.EXTRA_TEXT   , "body of email");
		try {
		    startActivity(Intent.createChooser(i, "Send mail..."));
		} catch (android.content.ActivityNotFoundException ex) {
		    Toast.makeText(Login.this, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
		}
		*/
	}
	
	/**
	 * Attempts to Register a user.
	 * If there are form errors (invalid fields, missing fields, etc.), the
	 * errors are presented and no actual registration attempt is made.
	 */
	public void attemptRegistration() {
		if (mAuthTask != null) {
			return;
		}

		Intent intent = new Intent(this, Registration1.class);
		startActivityForResult(intent,1);
		
	}
	
	
	String name="",email="",date="";
	ArrayList<String>dNameList=new ArrayList<String>(), dEmailList=new ArrayList<String>();
	ArrayList<String>cNameList=new ArrayList<String>(), cEmailList=new ArrayList<String>(), cPhoneList=new ArrayList<String>();
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		
        if (requestCode == 1) {
            if (resultCode == RESULT_OK) {
            	mUserName=data.getStringExtra("un");
            	mPassword=data.getStringExtra("pw");
            	name=data.getStringExtra("n");
            	date=data.getStringExtra("d");
            	email=data.getStringExtra("e");
            	
                startActivityForResult(new Intent(this, Registration2.class),2);
            }
        }
        if (requestCode == 2) {
            if (resultCode == 1)//no doctor information to retrieve
            	startActivityForResult(new Intent(this, Registration3.class),3);
            if(resultCode == 2) { //retrieve doctor information
            	Bundle b=data.getExtras();
            	dNameList=b.getStringArrayList("names");
            	dEmailList=b.getStringArrayList("emails");
                startActivityForResult(new Intent(this, Registration3.class),3);
            }
        }
        if (requestCode == 3) {
            if (resultCode == 2) { //retrieve contact information
            	Bundle b=data.getExtras();
            	cNameList=b.getStringArrayList("names");
            	cEmailList=b.getStringArrayList("emails");
            	cPhoneList=b.getStringArrayList("phones");
            	
            }
            if(resultCode != RESULT_CANCELED)
            {
	        	SharedPreferences.Editor editor = logins.edit();
	   		 	editor.putString(mUserName,mPassword);
	   		 	editor.commit();
	   		 	//add new user to database
	   		 	User u= new User(name, mUserName, mPassword, email, date);
	   		 	db.addUser(u);
	   		 	//add a user's doctors to the database
	   		 	if (!dNameList.isEmpty())
	       		 	for(int i=0; i<dNameList.size(); i++)
	       		 		db.addDoctor((new Doctor(dNameList.get(i),dEmailList.get(i))), mUserName);
	   		 	//add a user's contacts to the database
	   		 	if (!cNameList.isEmpty())
	       		 	for(int i=0; i<cNameList.size(); i++)
	       		 		db.addContact((new Contact(cNameList.get(i),cEmailList.get(i),cPhoneList.get(i))), mUserName);
	   		 	db.closeDB();
	   		    
	        	// Show a progress spinner, and kick off a background task to perform the user login attempt.
	    		mLoginStatusMessageView.setText(R.string.login_progress_signing_in);
	    		showProgress(true);
	    		mAuthTask = new UserLoginTask();
	    		mAuthTask.execute((Void) null);
            }
        }
	}
    

	/**Shows the progress UI and hides the login form.*/
	@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
	private void showProgress(final boolean show) {
		// On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
		// for very easy animations. If available, use these APIs to fade-in
		// the progress spinner.
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
			int shortAnimTime = getResources().getInteger(
					android.R.integer.config_shortAnimTime);

			mLoginStatusView.setVisibility(View.VISIBLE);
			mLoginStatusView.animate().setDuration(shortAnimTime)
					.alpha(show ? 1 : 0)
					.setListener(new AnimatorListenerAdapter() {
						@Override
						public void onAnimationEnd(Animator animation) {
							mLoginStatusView.setVisibility(show ? View.VISIBLE
									: View.GONE);
						}
					});

			mLoginFormView.setVisibility(View.VISIBLE);
			mLoginFormView.animate().setDuration(shortAnimTime)
					.alpha(show ? 0 : 1)
					.setListener(new AnimatorListenerAdapter() {
						@Override
						public void onAnimationEnd(Animator animation) {
							mLoginFormView.setVisibility(show ? View.GONE
									: View.VISIBLE);
						}
					});
		} else {
			// The ViewPropertyAnimator APIs are not available, so simply show
			// and hide the relevant UI components.
			mLoginStatusView.setVisibility(show ? View.VISIBLE : View.GONE);
			mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
		}
	}

	/**Represents an asynchronous login task used to authenticate the user.*/
	public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {
		@Override
		protected Boolean doInBackground(Void... params) {
			if (logins.contains(mUserName)) {
				// Account exists, return true if the password matches.
				if(logins.getString(mUserName,null).equals(mPassword))
					return true;
			}
			return false;
		}

		@Override
		protected void onPostExecute(final Boolean success) {
			mAuthTask = null;
			showProgress(false);

			if (success) {
				//set current user
				SharedPreferences.Editor editor = logins.edit();
       		 	editor.putString("currentUser",mUserName);
       		 	editor.commit();
				Intent intent = new Intent(Login.this, HomeScreen.class);
		    	startActivity(intent);
				finish();
			} else {
				// 1. Instantiate an AlertDialog.Builder with its constructor
				AlertDialog.Builder builder = new AlertDialog.Builder(Login.this);
				// 2. Chain together various setter methods to set the dialog characteristics
				builder.setMessage(getString(R.string.invalid_un_pw))
				       .setTitle(getString(R.string.error_login));
				builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
			           public void onClick(DialogInterface dialog, int id) {
			               // User clicked OK button
			           }
			       });
				// 3. Get the AlertDialog from create()
				AlertDialog dialog = builder.create();
				dialog.show();
				
			}
		}

		@Override
		protected void onCancelled() {
			mAuthTask = null;
			showProgress(false);
		}
	}
}
